package com.spremoteservice.android;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ListsService {
	
	private String _siteUrl;
	private String _userName;
	private String _password;
	
	public ListsService(String siteUrl, String userName, String password){
		this._siteUrl = siteUrl;
		this._userName = userName;
		this._password = password;
	}
	public List<ListViewSPObject> GetListCollection() throws ClientProtocolException, IOException, ParserConfigurationException, SAXException{
		List<ListViewSPObject> listCollection = new ArrayList<ListViewSPObject>();
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/Lists.asmx");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
	        
    	StringEntity se = new StringEntity("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><GetListCollection xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"/></s:Body></s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity resEntity = httpresponse.getEntity();

	    String GetListCollectionResult = EntityUtils.toString(resEntity);
	   
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        
    	DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(GetListCollectionResult)));
        NodeList listNodeList = doc.getElementsByTagName("List");
        
        for (int i = 0; i< listNodeList.getLength(); i++){
        	Node listNode = listNodeList.item(i);
        	NamedNodeMap atts = listNode.getAttributes();
			String libraryId = atts.getNamedItem("ID").getNodeValue();
			String title = atts.getNamedItem("Title").getNodeValue();
        	String baseType = atts.getNamedItem("BaseType").getNodeValue();
        	String hidden = atts.getNamedItem("Hidden").getNodeValue();
        	if(baseType.equals("1") && hidden.equals("False")){
            	//Create object
            	ListViewSPObject list = new ListViewSPObject(libraryId, "Library", title,
            			_siteUrl, libraryId, title, "", "");
            	listCollection.add(list);
        	}
        }

        return listCollection;
	}
	
	public List<ListViewSPObject> GetFolderCollection(String listName, String libraryId, String libPath) throws ClientProtocolException, IOException, ParserConfigurationException, SAXException{
		List<ListViewSPObject> folderCollection = new ArrayList<ListViewSPObject>();
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/Lists.asmx");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
	        
    	StringEntity se = new StringEntity("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><listName>" + listName + "</listName><query><Query xmlns=\"\"><Where><And><IsNull><FieldRef Name=\"DocIcon\"/></IsNull><Eq><FieldRef Name=\"FSObjType\"/><Value Type=\"Lookup\">1</Value></Eq></And></Where></Query></query><viewFields><ViewFields xmlns=\"\"><FieldRef Name=\"LinkFilename\"/><FieldRef Name=\"DocIcon\"/><FieldRef Name=\"UniqueId\"/><FieldRef Name=\"FileLeafRef\"/><FieldRef Name=\"FileRef\"/><FieldRef Name=\"ID\"/><FieldRef Name=\"HTML File Type\"/></ViewFields></viewFields><rowLimit>2147483647</rowLimit><webID/></GetListItems></s:Body></s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity resEntity = httpresponse.getEntity();

	    String GetFolderCollectionResult = EntityUtils.toString(resEntity);
	   
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
	        
    	DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(GetFolderCollectionResult)));
        NodeList folderNodeList = doc.getElementsByTagNameNS("#RowsetSchema", "row");
        //NodeList folderNodeList = doc.getElementsByTagNameNS("*", "row");
        //NodeList folderNodeList = doc.getElementsByTagName("row");
        
        for (int i = 0; i< folderNodeList.getLength(); i++){
        	Node folderNode = folderNodeList.item(i);
        	NamedNodeMap atts = folderNode.getAttributes();
			String folderId = GetDisplayString(atts.getNamedItem("ows_UniqueId").getNodeValue());
			String folderName = GetDisplayString(atts.getNamedItem("ows_FileLeafRef").getNodeValue());
			String folderPath = GetDisplayString(atts.getNamedItem("ows_FileRef").getNodeValue());
			//Create object
			ListViewSPObject folder = new ListViewSPObject(folderId, "Folder", folderName,
					_siteUrl, libraryId, listName, folderPath, "");
			folderCollection.add(folder);
        }

        return folderCollection;
	}
	
	public List<ListViewSPObject> GetDocumentCollection(String listName, String libraryId, String libPath) throws ClientProtocolException, IOException, ParserConfigurationException, SAXException{
		List<ListViewSPObject> documentCollection = new ArrayList<ListViewSPObject>();
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/Lists.asmx");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
	        
    	StringEntity se = new StringEntity(
    			"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
    			"	<s:Body>" +
    			"		<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
    			"			<listName>" + listName + "</listName>" +
    			"			<query>" +
    			"				<Query xmlns=\"\">" +
    			"					<Where>" +
    			"							<Neq>" +
    			"								<FieldRef Name=\"FSObjType\"/>" +
    			"								<Value Type=\"Lookup\">1</Value>" +
    			"							</Neq>" +
    			"					</Where>" +
    			"				</Query>" +
    			"			</query>" +
    			"			<viewFields>" +
    			"				<ViewFields xmlns=\"\">" +
    			"					<FieldRef Name=\"LinkFilename\"/>" +
    			"					<FieldRef Name=\"DocIcon\"/>" +
    			"					<FieldRef Name=\"UniqueId\"/>" +
    			"					<FieldRef Name=\"FileLeafRef\"/>" +
    			"					<FieldRef Name=\"FileRef\"/>" +
    			"					<FieldRef Name=\"ID\"/>" +
    			"					<FieldRef Name=\"HTML File Type\"/>" +
    			"				</ViewFields>" +
    			"			</viewFields>" +
    			"			<rowLimit>2147483647</rowLimit>" +
    			"			<webID/>" +
    			"		</GetListItems>" +
    			"	</s:Body>" +
    			"</s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity resEntity = httpresponse.getEntity();

	    String GetFolderCollectionResult = EntityUtils.toString(resEntity);
	   
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
	        
    	DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(GetFolderCollectionResult)));
        NodeList documentNodeList = doc.getElementsByTagNameNS("#RowsetSchema", "row");
        
        for (int i = 0; i< documentNodeList.getLength(); i++){
        	Node documentNode = documentNodeList.item(i);
        	NamedNodeMap atts = documentNode.getAttributes();
			String documentId = GetDisplayString(atts.getNamedItem("ows_UniqueId").getNodeValue());
			String documentName = GetDisplayString(atts.getNamedItem("ows_FileLeafRef").getNodeValue());
			String folderPath = GetDisplayString(atts.getNamedItem("ows_FileRef").getNodeValue());
			//Create object
			ListViewSPObject document = new ListViewSPObject(documentId, "Document", documentName,
					_siteUrl, libraryId, listName, folderPath, documentName);
			documentCollection.add(document);
        }

        return documentCollection;
	}

	public String GetDisplayString(String str){
		int idx = str.indexOf("#");
		return str.substring(idx + 1, str.length());
	}
}
